package is.ru.honn.rumblr.util;

import is.ru.honn.rumblr.domain.RumblrLog;
import is.ru.honn.rumblr.factory.PostFactory;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import java.util.List;

public class RubmlrParser
{
  protected Document document;
  protected RumblrLog rumblrLog;

  public RumblrLog parse(Document document) throws Exception
  {
    this.document = document;
    this.rumblrLog = new RumblrLog();

    Element root = document.getRootElement();

    rumblrLog.setName(XmlUtil.getXPathValue(root, "//tumblr/tumblelog/@name"));
    rumblrLog.setTitle(XmlUtil.getXPathValue(root, "//tumblr/tumblelog/@title"));

    List<Node> posts = (List<Node>) root.selectNodes("//tumblr/posts/post");

    for (Node postNode : posts)
    {
      rumblrLog.addPost(PostFactory.createPost((Element) postNode));
    }

    return getRumblrLog();
  }

  public Document getDocument()
  {
    return document;
  }

  public RumblrLog getRumblrLog()
  {
    return rumblrLog;
  }
}
